const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import {
  showMsg
} from '../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../utils/validate.js'
import {
  reqSpaceAdd,
  reqSpaceBatchAdd
} from '../../../../request/api'
Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    // parkId: '', //园区id
    pid: '', //父id
    form: {
      name: '', //单个添加楼层名称
      isDefence: true,
      metaCode: 2, //空间类型 
      buildingType: 2,
      childrenName: [], //批量新增下级空间名称
    },
    radio: "1", //单个添加/批量添加
    batchNameList: [{
      id: 0,
      start: '',
      end: ''
    }, ], //批量添加
    disabledBtn: false,
  },
  onLoad(e) {
    this.getParkId(e)
  },
  // 获取id
  getParkId(e) {
    let params = JSON.parse(e.params)
    console.log(params);
    this.setData({
      // parkId: params.parkId,
      orgId: params.orgId,
      pid: params.pid
    })
  },
  // 点击布撤防
  changeDefence(e) {
    let tip = e.detail ? '此操作将开启该楼层所有设备布防设置，是否继续？' : '此操作将关闭该楼层所有设备布防设置，是否继续？'
    Dialog.confirm({
        title: '温馨提示',
        message: tip,
      })
      .then(async () => {
        this.setData({
          "form.isDefence": e.detail
        })
      })
      .catch(() => {});
  },

  // 选择单个添加/批量添加
  radioChange(e) {
    this.setData({
      radio: e.detail
    })
  },
  // 单个添加获取名称
  nameChange(e) {
    // 正则表达式
    let value = e.detail.value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value = value.replace(/\-{2,}/g, "-"); // -只能保留一个
    value = value.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value = value.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value = value.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value > 50) {
      value = 50
    }
    if (value < -3) {
      value = -3
    }
    if (value == '0') {
      value = 1
    }
    // let value = this.validateNumber(e.detail.value)
    this.setData({
      "form.name": value
    })
  },
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },
  // 单个添加清除
  clearname() {
    this.setData({
      'form.name': ''
    })
  },
  // 点击新增一条楼层段
  clickAddFloor() {
    let {
      batchNameList
    } = this.data
    if (batchNameList.length > 1) return Toast('最多只允许添加两个楼层信息');
    let id = batchNameList.length === 0 ? 0 : batchNameList[batchNameList.length - 1].id + 1
    batchNameList.push({
      id,
      start: '',
      end: ''
    })
    this.setData({
      batchNameList
    })
  },
  // 获取开始层数
  floorStartChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    let {
      batchNameList
    } = this.data
    // 正则表达式
    let value2 = value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value2 = value2.replace(/\-{2,}/g, "-"); // -只能保留一个
    value2 = value2.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value2 = value2.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value2 = value2.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value2 > 49) {
      value2 = 49
    }
    if (value2 < -3) {
      value2 = -3
    }
    if (value2 == '0') {
      value2 = 1
    }
    batchNameList.forEach(item => {
      if (item.id === id) {
        item.start = value2
      }
    })
    this.setData({
      batchNameList
    })
  },

  // 获取结束层数
  floorEndeChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    let {
      batchNameList
    } = this.data
    // 正则表达式
    let value2 = value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value2 = value2.replace(/\-{2,}/g, "-"); // -只能保留一个
    value2 = value2.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value2 = value2.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value2 = value2.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value2 > 50) {
      value2 = 50
    }
    if (value2 < -3) {
      value2 = -3
    }
    if (value2 == '0') {
      value2 = 1
    }
    batchNameList.forEach(item => {
      if (item.id === id) {
        item.end = value2
      }
    })
    this.setData({
      batchNameList
    })
  },
  // 删除一条
  deleteBatchName(e) {
    let {
      id
    } = e.target.dataset
    let {
      batchNameList
    } = this.data
    batchNameList.splice(id, 1)
    batchNameList.forEach((item, index) => {
      item.id = index
    })
    this.setData({
      batchNameList
    })
  },

  //  确认新增楼层
  confirm() {
    if (this.data.disabledBtn) return
    let {
      radio,
      batchNameList,
      form
    } = this.data
    if (radio == 2) {
      let params = {
        pid: this.data.pid,
        nameList: []
      }
      let arr = []
      let flag = false
      let flag1 = false
      let index = 0
      let index1 = 0
      try {
        batchNameList.forEach(item => {
          if (item.start > item.end) {
            index = item.id + 1
            flag = true
            throw new console.log(`第${index}项错误`);
          }
          if (item.start === '') {
            flag1 = true
            index1 = item.id + 1
            throw new console.log(`第${index1}项错误`);
          }
          for (let i = item.start; i <= item.end; i++) {
            console.log(i);
            if (i != 0) {
              arr.push(`${i}层`)
            }
          }
        })
      } catch (e) {
        console.log(e);
      }
      if (flag) return showMsg(`第${index}项结束楼层小于开始楼层，请检查！`)
      if (flag1) return showMsg(`第${index1}项开始楼层数未填写，请检查！`)
      params.nameList = Array.from(new Set(arr));
      params.nameList.forEach((item, index) => {
        if (!item) {
          params.nameList.splice(index, 1)
        }
      })
      if (!params.nameList[0]) return showMsg("请输入")
      if (params.nameList.length > 50) return showMsg("一次最多添加50个楼层")
      this.reqSpaceBatchAddFun(params)
    } else {
      if (!(form.name)) return showMsg("请输入名称")
      if (!validateSpecial(form.name)) return
      let params = {
        orgId: this.data.orgId,
        pid: this.data.pid,
        name: form.name + '层',

        lng: '',
        lat: '',
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        area: '',
        areaCode: '',
        street: '',
        streetCode: '',
        address: '',

        isDefence: form.isDefence ? 1 : 0,
        // metaCode: form.metaCode,
        buildingType: form.buildingType,
        childrenName: [],
        picList: [],
        village: ''
      }
      this.reqSpaceAddFun(params)
    }

  },
  // 单个添加
  async reqSpaceAddFun(params) {
    const res = await reqSpaceAdd(params)
    if (res.code != 20000) return showMsg(res.message)
    showMsg("新增成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000)
  },

  // 批量添加
  async reqSpaceBatchAddFun(params) {
    const res = await reqSpaceBatchAdd(params)
    if (res.code != 20000) return showMsg(res.message)
    showMsg("新增成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000)
  },
})